<template>
  <div>
    <div style="height: 230px">
      <n-scrollbar trigger="none">
        <n-space vertical>
          <n-input
              v-model:value="row.advancePrompt.mainObj"
              style="height: 60px;" type="textarea"
              @update:value="updateBoard" placeholder="">
            <template #prefix>
              <n-tooltip trigger="hover">
                <template #trigger>
                  <n-space justify="center">
                    <n-text>
                      主体
                    </n-text>
                    <n-divider vertical></n-divider>
                  </n-space>
                </template>
                中心主题的特征（例如人物、物体、动物），包括外观、颜色和独特特征。
              </n-tooltip>
            </template>
          </n-input>
          <n-grid x-gap="5">
            <n-grid-item :span="12">
              <n-auto-complete
                  v-model:value="row.advancePrompt.expression"
                  :append="true"
                  :get-show="getExpressionPrompt"
                  :options="expressAutoCompletion"
                  placeholder=""
                  @focus="queryEnable.expression = true"
                  @blur="queryEnable.expression = false"
                  :render-label="renderLabel"
                  @update:value="(value:string)=> updateValue(value,'expression')"
                  @select="optionSelect"
              >
                <template #prefix>
                  <n-tooltip trigger="hover">
                    <template #trigger>
                      <n-space justify="center">
                        <n-text>
                          表情
                        </n-text>
                        <n-divider vertical></n-divider>
                      </n-space>
                    </template>
                    表情（愤怒、快乐、悲伤、惊讶）
                  </n-tooltip>
                </template>
              </n-auto-complete>
            </n-grid-item>

            <n-grid-item :span="12">
              <n-auto-complete
                  v-model:value="row.advancePrompt.action"
                  :append="true"
                  :get-show="getActionPrompt"
                  :options="actionAutoCompletion"
                  placeholder=""
                  @focus="queryEnable.action = true"
                  @blur="queryEnable.action = false"
                  :render-label="renderLabel"
                  @update:value="(value:string)=>updateValue(value,'action')"
                  @select="optionSelect"
              >
                <template #prefix>
                  <n-tooltip trigger="hover">
                    <template #trigger>
                      <n-space justify="center">
                        <n-text>
                          动作
                        </n-text>
                        <n-divider vertical></n-divider>
                      </n-space>
                    </template>
                    动作（跑、跳、飞、游泳）和姿势。
                  </n-tooltip>
                </template>
              </n-auto-complete>
            </n-grid-item>
          </n-grid>
            <n-auto-complete
                v-model:value="row.advancePrompt.background"
                :append="true"
                :options="backgroundAutoCompletion"
                :get-show="getBackgroundPrompt"
                placeholder=""
                :render-label="renderLabel"
                @focus="queryEnable.background = true"
                @blur="queryEnable.background = false"
                @update:value="(value:string)=>updateValue(value,'background')"
                @select="optionSelect"
            >
              <template #prefix>
                <n-tooltip trigger="hover">
                  <template #trigger>
                    <n-space justify="center">
                      <n-text>
                        场景
                      </n-text>
                      <n-divider vertical></n-divider>
                    </n-space>
                  </template>
                  地点（室内、室外、虚构）、环境元素（自然、城市）、时间和天气条件。
                </n-tooltip>
              </template>
            </n-auto-complete>

          <n-auto-complete
              v-model:value="row.advancePrompt.camera"
              :append="true"
              :options="cameraAutoCompletion"
              :get-show="getCameraPrompt"
              placeholder=""
              :render-label="renderLabel"
              @focus="queryEnable.camera = true"
              @blur="queryEnable.camera = false"
              @update:value="(value:string)=>updateValue(value,'camera')"
              @select="optionSelect"
          >
            <template #prefix>
              <n-tooltip trigger="hover">
                <template #trigger>
                  <n-space justify="center">
                    <n-text>
                      视角
                    </n-text>
                    <n-divider vertical></n-divider>
                  </n-space>
                </template>
                视角（特写、广角、航拍）、角度和具体的构图偏好。
              </n-tooltip>
            </template>
          </n-auto-complete>
          <n-auto-complete
              v-model:value="row.advancePrompt.light"
              :append="true"
              :options="lightAutoCompletion"
              :get-show="getLightPrompt"
              placeholder=""
              :render-label="renderLabel"
              @focus="queryEnable.light = true"
              @blur="queryEnable.light = false"
              @update:value="(value:string)=>updateValue(value,'light')"
              @select="optionSelect"
          >
            <template #prefix>
              <n-tooltip trigger="hover">
                <template #trigger>
                  <n-space justify="center">
                    <n-text>
                      光效
                    </n-text>
                    <n-divider vertical></n-divider>
                  </n-space>
                </template>
                照明类型（明亮、昏暗、自然光）、情绪（愉快、神秘）和大气效果。
              </n-tooltip>
            </template>
          </n-auto-complete>
        </n-space>
      </n-scrollbar>
    </div>
  </div>
</template>

<script setup lang="ts">
//@ts-ignore
import fileFunction from '@/libs/globalFunction/file.js'
import {NTag} from "naive-ui";
import {computed, h, ref} from "vue";
import {useMessage} from 'naive-ui';
import {storyBoardController} from "@/api/controller/story/storyBoard.api";

const actionAutoCompletion = ref([])
const expressAutoCompletion = ref([])
const cameraAutoCompletion = ref([])
const backgroundAutoCompletion = ref([])
const lightAutoCompletion = ref([])

const message = useMessage()
const loading = ref(false)
const selectedValue = ref('')
import {userTagStore} from '@/store/tag/tagStore';
import {ArrowDown, ArrowUp} from "@vicons/ionicons5";
import {tagCategoryController} from "@/api/controller/tagcategory/tagCategoryController";
const searchTagValue = ref('')

const dictionaryStore = userTagStore();

const queryEnable = ref({
  action: false,
  expression: false,
  camera: false,
  light: false,
  background: false
})


const props = defineProps({
  row: {
    type: Object,
    default: () => {
      return {}
    }
  },
  weightOpen: {
    type: Boolean,
    default: false
  },
  selectFunction: {
    type: Function,
    // required: true
    default: (fileId: string) => {

    }
  }
})


const mainObjTags = computed(() => {
  if (props.row.advancePrompt.mainObj === '' || props.row.advancePrompt.mainObj === null) {
    return []
  }
  return getTags(props.row.advancePrompt.mainObj)
})

const getTags = (promptTags:any) => {
  const splitTags = promptTags.split(',')
  for (let i = 0; i < splitTags.length; i++) {
    if (splitTags[i] === '') {
      splitTags.splice(i, 1)
    }
  }
  return splitTags
}


const expressTags = computed(() => {
  if (props.row.advancePrompt.expression === '' || props.row.advancePrompt.expression === null) {
    return []
  }
  return getTags(props.row.advancePrompt.expression)
})



const updateValue = (promptString: string,code:string) => {
  if (props.row.advancePrompt.action){
    props.row.advancePrompt.action = props.row.advancePrompt.action.replace(/，/g, ',');
  }
  if (props.row.advancePrompt.expression){
    props.row.advancePrompt.expression = props.row.advancePrompt.expression.replace(/，/g, ',');
  }
  if (props.row.advancePrompt.camera){
    props.row.advancePrompt.camera = props.row.advancePrompt.camera.replace(/，/g, ',');
  }
  if (props.row.advancePrompt.background){
    props.row.advancePrompt.background = props.row.advancePrompt.background.replace(/，/g, ',');
  }
  if (props.row.advancePrompt.light){
    props.row.advancePrompt.light = props.row.advancePrompt.light.replace(/，/g, ',');
  }
  if ( promptString == '' || updateValue == null
      || promptString=='null'
      || searchTagValue.value == ''
      || selectedValue.value == '') {
    if (code === 'action') {
      props.row.advancePrompt.action =  props.row.advancePrompt.action.replaceAll("null","")
    }else if(code === 'expression'){
      props.row.advancePrompt.expression =  props.row.advancePrompt.expression.replaceAll("null","")
    }else if(code === 'camera') {
      props.row.advancePrompt.camera = props.row.advancePrompt.camera.replaceAll("null", "")
    }else if(code === 'background') {
      props.row.advancePrompt.background = props.row.advancePrompt.background.replaceAll("null", "")
    }else if(code === 'light') {
      props.row.advancePrompt.light = props.row.advancePrompt.light.replaceAll("null", "")
    }
    selectedValue.value = ''
    searchTagValue.value = ''
    updateBoard()
    return
  }
  const markIndex = promptString.lastIndexOf(",")
  if(markIndex == -1){
    if (code == 'action') {
      props.row.advancePrompt.action = selectedValue.value
    }else if (code == 'expression') {
      props.row.advancePrompt.expression = selectedValue.value
    }else if (code == 'camera') {
      props.row.advancePrompt.camera = selectedValue.value
    } else if (code == 'background') {
      props.row.advancePrompt.background = selectedValue.value
    }else if (code == 'light') {
      props.row.advancePrompt.light = selectedValue.value
    }
  }else {
    const lastValue = promptString.substring(0,markIndex )
    if (code == 'action') {
      props.row.advancePrompt.action = lastValue + ',' + selectedValue.value
    }else if (code == 'expression') {
      props.row.advancePrompt.expression = lastValue + ',' + selectedValue.value
    }else if (code == 'camera') {
      props.row.advancePrompt.camera = lastValue + ',' + selectedValue.value
    }else if (code == 'background') {
      props.row.advancePrompt.background = lastValue + ',' + selectedValue.value
    }else if (code == 'light') {
      props.row.advancePrompt.light = lastValue + ',' + selectedValue.value
    }
  }
  selectedValue.value = ''
  searchTagValue.value = ''
  updateBoard()
}




const renderLabel = (option: any) => {
  return [
    option.label as string,
    ' ',
    h(NTag, {size: 'small', type: 'info'}, {default: () => option.category})
  ]
}



const optionSelect = (value: string) => {
  selectedValue.value = value
}

const getActionPrompt = async (value: string) => {
  if (queryEnable.value.action === false) {
    return
  }
  actionAutoCompletion.value = []
  searchTagValue.value = searchValue(value)
  const data ={
    categoryCode: '0305',
    search : searchTagValue.value
  }
  const res = await tagCategoryController.autoCompletion(data)
  if (res.code == 200) {
    actionAutoCompletion.value = res.data.map((item:any) => {
      return {
        label: item.zh,
        value: item.en,
        category: item.categoryName
      }
    })
    return true
  }else {
    return false
  }

}


const getExpressionPrompt = async (value: string) => {
  if (queryEnable.value.expression === false) {
    return
  }
  expressAutoCompletion.value =[]
  searchTagValue.value = searchValue(value)
  const data ={
    categoryCode: '0306',
    search : searchTagValue.value
  }
  const res = await tagCategoryController.autoCompletion(data)
  if (res.code == 200) {
    expressAutoCompletion.value = res.data.map((item:any) => {
      return {
        label: item.zh,
        value: item.en,
        category: item.categoryName
      }
    })
    return true
  }else {
    return false
  }
}


const getCameraPrompt =async  (value: string) => {
  if (queryEnable.value.camera === false) {
    return
  }
  cameraAutoCompletion.value =[]
  const data ={
    categoryCode: '030103',
    search : searchTagValue.value
  }
  const res = await tagCategoryController.autoCompletion(data)
  if (res.code == 200) {
    cameraAutoCompletion.value = res.data.map((item:any) => {
      return {
        label: item.zh,
        value: item.en,
        category: item.categoryName
      }
    })
    return true
  }else {
    return false
  }
}


const getBackgroundPrompt = async (value: string) => {
  if (queryEnable.value.background === false) {
    return
  }
  backgroundAutoCompletion.value =[]
  searchTagValue.value = searchValue(value)
  const data ={
    categoryCode: '0307',
    search : searchTagValue.value
  }
  const res = await tagCategoryController.autoCompletion(data)
  if (res.code == 200) {
    backgroundAutoCompletion.value = res.data.map((item:any) => {
      return {
        label: item.zh,
        value: item.en,
        category: item.categoryName
      }
    })
    return true
  }else {
    return false
  }
}


const getLightPrompt = async (value: string) => {
  if (queryEnable.value.light === false) {
    return
  }
  lightAutoCompletion.value =[]
  searchTagValue.value = searchValue(value)
  const data ={
    categoryCode: '030106',
    search : searchTagValue.value
  }
  const res = await tagCategoryController.autoCompletion(data)
  if (res.code == 200) {
    lightAutoCompletion.value = res.data.map((item:any) => {
      return {
        label: item.zh,
        value: item.en,
        category: item.categoryName
      }
    })
    return true
  }else {
    return false
  }
}


const searchFromTagDic = (search:string,tagArray:any)=>{
  const searchArray = []
  for (let i = 0; i < tagArray.length; i++) {
    if (tagArray[i].zh.indexOf(search) != -1 || tagArray[i].en.indexOf(search) != -1){
      if (tagArray[i].zh != search && tagArray[i].en != search) {
       let contains = false;
       for (let j = 0; j < searchArray.length; j++) {
          if (searchArray[j].value === tagArray[i].en) {
            contains = true
          }
       }
       if (!contains) {
          searchArray.push(
              {
                label: tagArray[i].zh,
                value: tagArray[i].zh,
                category: tagArray[i].categoryName
              } )
       }
      }
    }
  }
  return searchArray
}


const searchValue = (typeValue:string) =>{
  let result = ''; // 使用不同的变量名以避免冲突
  const markIndex = typeValue.lastIndexOf(",")
  if (markIndex === -1) {
    // 如果没有找到逗号或者字符串以逗号结尾，使用整个字符串
    result = typeValue;
  } else {
    // 否则，截取逗号后面的内容
    result = typeValue.substring(markIndex + 1);
  }
  return result;
}


const updateBoard = () => {
  props.row.advancePrompt.mainObj = props.row.advancePrompt.mainObj.replace(/，/g, ',');
  const param = {...props.row}
  delete param.characterList
  storyBoardController.addOrUpdateBoard(param).then(res => {
    if (res.code !== 200) {
      message.error(res.msg)
    }
  })
}

</script>

<style>
</style>
